﻿using Microsoft.EntityFrameworkCore;
using YougeBookmark.Models;
using System.Linq;
using Microsoft.EntityFrameworkCore.Storage;
//using System.Data.Entity;

//using DbContext = Microsoft.EntityFrameworkCore.DbContext;


namespace YougeBookmark.Data
{
    public class DatabaseContext : DbContext
    {
        // 实体集合定义
        public DbSet<Bookmark> Bookmarks { get; set; }
        public DbSet<Tag> Tags { get; set; }
        public DbSet<BookmarkTag> BookmarkTags { get; set; }

        /// <summary>
        /// SQLite数据库文件路径配置（自动创建AppData目录）
        /// </summary>
        private readonly string _dbPath = System.IO.Path.Combine(
            /*Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData)*/AppDomain.CurrentDomain.BaseDirectory,
            "YougeBookmark",
            "bookmarks.db"
        );

        public IDbContextTransaction BeginTransaction(System.Data.IsolationLevel isolationLevel = System.Data.IsolationLevel.ReadCommitted)
        {
            return Database.BeginTransaction(isolationLevel);            
        }
        protected override void OnConfiguring(DbContextOptionsBuilder options)
        {
            Directory.CreateDirectory(Path.GetDirectoryName(_dbPath)!); // 确保目录存在
            options.UseSqlite($"Data Source={_dbPath}");
        }

        protected override void OnModelCreating(ModelBuilder modelBuilder)
        {
            // Bookmark表配置
            modelBuilder.Entity<Bookmark>(entity =>
            {
                entity.HasKey(b => b.Id);
                entity.Property(b => b.CreatedAt)
                    .HasDefaultValueSql("CURRENT_TIMESTAMP");
                entity.HasIndex(b => b.Url).IsUnique();
            });

            // Tag表配置
            modelBuilder.Entity<Tag>(entity =>
            {
                entity.HasKey(t => t.Id);
                entity.HasIndex(t => t.Name).IsUnique();
                entity.Property(t => t.Name).HasMaxLength(100);
                entity.Property(t => t.CreatedAt)
                    .HasDefaultValueSql("CURRENT_TIMESTAMP");
            });

            // BookmarkTag关联表配置
            modelBuilder.Entity<BookmarkTag>(entity =>
            {
                entity.HasKey(bt => bt.Id);
                entity.Property(bt => bt.CreatedAt)
                    .HasDefaultValueSql("CURRENT_TIMESTAMP");

                // 建立复合唯一索引
                entity.HasIndex(bt => new { bt.BookmarkId, bt.TagId }).IsUnique();

                // 配置与Bookmark的双向关系
                entity.HasOne(bt => bt.Bookmark)
                    .WithMany(b => b.BookmarkTags)
                    .HasForeignKey(bt => bt.BookmarkId)
                    .OnDelete(DeleteBehavior.Cascade);

                // 配置与Tag的双向关系
                entity.HasOne(bt => bt.Tag)
                    .WithMany(t => t.BookmarkTags)
                    .HasForeignKey(bt => bt.TagId)
                    .OnDelete(DeleteBehavior.Cascade);
            });

            //// 书签标签关联配置
            //modelBuilder.Entity<BookmarkTag>(entity =>
            //{
            //    entity.HasKey(bt => new { bt.BookmarkId, bt.TagId });

            //    entity.HasOne(bt => bt.Bookmark)
            //        .WithMany(b => b.BookmarkTags)
            //        .HasForeignKey(bt => bt.BookmarkId)
            //        .OnDelete(DeleteBehavior.Cascade);

            //    entity.HasOne(bt => bt.Tag)
            //        .WithMany(t => t.BookmarkTags)
            //        .HasForeignKey(bt => bt.TagId)
            //        .OnDelete(DeleteBehavior.Cascade);
            //});


            // SQLite不支持Decimal类型，显式指定类型
            modelBuilder.Entity<Bookmark>()
                .Property(b => b.Url)
                .HasColumnType("TEXT");

            // 配置SQLite日期类型映射
            modelBuilder.Entity<Bookmark>()
                .Property(b => b.CreatedAt)
                .HasColumnType("DATETIME");
        }

        /// <summary>
        /// 数据库初始化（首次运行时自动创建）
        /// </summary>
        public void Initialize()
        {
            Database.Migrate(); // 自动应用未执行的迁移
            Database.EnsureCreated(); // 确保表结构存在
        }
    }
}